#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# File  : main.py
# Author: DaShenHan&道长-----先苦后甜，任凭晚风拂柳颜------
# Date  : 2019/7/22

import markdown
import shutil
import os
import codecs


css_begin = '''
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
<title>GitHub Markdown CSS demo</title>
<link rel="stylesheet" href="https://sindresorhus.com/github-markdown-css/github-markdown.css">
<style>
	@media (min-width: 768px) {
		.markdown-body {
			box-sizing: border-box;
			min-width: 200px;
			max-width: 980px;
			margin: 0 auto;
			padding: 45px;
		}
	}
</style>
</head>
<body>
<article class="markdown-body">
'''
css_end='''
</article>
</body>
'''
def md2html(inputfile="./remind.md", outdir="./htmls/"):
    f = codecs.open(inputfile, 'r', encoding='utf-8')
    readme_content = f.read()
    f.close()
    _, filename, _ = get_filePath_fileName_fileExt(inputfile)
    htmlname = filename + ".html"
    html = markdown.markdown(readme_content)
    html =css_begin + html + css_end
    f = open(outdir + htmlname, 'w+', encoding='utf-8')
    f.write(html)
    f.close()


def get_filePath_fileName_fileExt(fileUrl):  # 获取文件上级目录,文件名称，文件后缀
    filepath, tmpfilename = os.path.split(fileUrl)
    shotname, extension = os.path.splitext(tmpfilename)
    return filepath, shotname, extension


def fenlei(rootDir="./"):
    if not os.path.exists("mds"):
        os.mkdir("mds")
    if not os.path.exists("htmls"):
        os.mkdir("htmls")
    for lists in os.listdir(rootDir):
        if os.path.isfile(lists) and lists[-3:] == '.md':
            path = os.path.join(rootDir, lists)
            print("发现md文件: " + path)
            if not os.path.exists("./mds/" + path):
                shutil.copy(path, "./mds")
            continue
        # 如果找到的是文件夹，则判断，如果名称小于2则递归
        if os.path.isdir(lists) and lists != "mds" and lists != "htmls":
            path = os.path.join(rootDir, lists)
            print("path" + path)
            if os.path.isdir(path):
                fenlei(path)
    mdlists = []
    for lists in os.listdir("./mds"):
        path = os.path.join("./mds", lists)
        mdlists.append(path)
    return mdlists


if __name__ == '__main__':
    mdlists = fenlei()
    print("md文件列表:",mdlists)
    for inputfile in mdlists:
        md2html(inputfile)
